"use client";
import { Button } from "@/components/ui/button";
import { CardTitle } from "@/components/ui/card";
import { useTranslations } from "next-intl";
import { useState, useEffect } from "react";
import { getLeadsByUserId, LeadData, getPublicDetails, updateLeadDetails, deleteLead, updateLeadValidity } from "@/controller/leads";
import { toast } from "sonner";
import { CheckCircle, XCircle, Loader2, Info, Save, Edit, X, Trash2 } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import dayjs from 'dayjs';
export default function Leads() {
  const t = useTranslations('leads');
  const commonT = useTranslations('common');
  const [loading, setLoading] = useState(false);
  const [leads, setLeads] = useState<LeadData[]>([]);
  const [leadToDelete, setLeadToDelete] = useState<string | null>(null);
  const [deleteAlertOpen, setDeleteAlertOpen] = useState(false);
  const [deletingLeadId, setDeletingLeadId] = useState<string | null>(null);
  const [selectedLead, setSelectedLead] = useState<LeadData | null>(null);
  const [editScore, setEditScore] = useState<number | null>(null);
  const [editReason, setEditReason] = useState<string>('');
  const [isEditing, setIsEditing] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [creatorDetails, setCreatorDetails] = useState<any>(null);
  const [postDetails, setPostDetails] = useState<any>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [updatingLeadId, setUpdatingLeadId] = useState<string | null>(null);
  const fetchLeads = async () => {
    setLoading(true);
    const { data, error } = await getLeadsByUserId();
    if (error && !data) {
      toast.error(error?.toString() || 'Failed to get leads');
    } else {
      setLeads(data || []);
    }
    setLoading(false);
  };
  // 获取线索类型标签
  const getTypeLabel = (type: 'post' | 'comment' | 'creator') => {
    switch (type) {
      case 'post':
        return t('typePost');
      case 'comment':
        return t('typeComment');
      case 'creator':
        return t('typeCreator');
      default:
        return type;
    }
  };
  // 开始编辑
  const startEditing = () => {
    setIsEditing(true);
  };

  // 取消编辑
  const cancelEditing = () => {
    if (selectedLead) {
      setEditScore(selectedLead.lead_score !== undefined ? selectedLead.lead_score : null);
      setEditReason(selectedLead.reason || '');
    }
    setIsEditing(false);
  };
  // 保存编辑
  const saveEditing = async () => {
    if (!selectedLead) return;

    setIsSaving(true);
    const { data, error } = await updateLeadDetails(
      selectedLead.lead_id,
      editScore,
      editReason
    );

    if (error) {
      toast.error(error?.toString() || 'Failed to update lead details');
    } else if (data) {
      // 更新本地数据
      setLeads(prevLeads =>
        prevLeads.map(lead =>
          lead.lead_id === selectedLead.lead_id ?
            { ...lead, lead_score: editScore, reason: editReason } : lead
        )
      );
      setSelectedLead({ ...selectedLead, lead_score: editScore, reason: editReason });
      setIsEditing(false);
      toast.success(commonT('success'), {
        description: t('detailsUpdated')
      });
    }
    setIsSaving(false);
  };
  // 打开详情弹窗
  const openLeadDetails = (lead: LeadData) => {
    setSelectedLead(lead);
    setEditScore(lead.lead_score !== undefined ? lead.lead_score : null);
    setEditReason(lead.reason || '');
    setIsEditing(false);
    setDialogOpen(true);
    getPublicDetails(lead.type, lead.target_id).then(res => {
      if (res.error) {
        toast.error(res.error);
      } else {
        if (lead.type === 'creator') {
          setCreatorDetails(res.data);
        } else if (lead.type === 'post') {
          setPostDetails(res.data);
        }
      }
    })
  };
  // 打开删除确认对话框
  const openDeleteConfirm = (leadId: string) => {
    setLeadToDelete(leadId);
    setDeleteAlertOpen(true);
  };

  // 删除线索
  const handleDeleteLead = async () => {
    if (!leadToDelete) return;

    setDeletingLeadId(leadToDelete);
    setDeleteAlertOpen(false);

    const { data, error } = await deleteLead(leadToDelete);

    if (error || !data) {
      toast.error(error?.toString() || 'Failed to delete lead');
    } else {
      toast.success(commonT('success'), {
        description: t('deleteSuccess')
      });
      // 更新本地数据
      setLeads(prevLeads => prevLeads.filter(lead => lead.lead_id !== leadToDelete));
    }
    setDeletingLeadId(null);
    setLeadToDelete(null);
  };
  // 更新线索有效性
  const handleUpdateValidity = async (leadId: string, isValid: boolean) => {
    setUpdatingLeadId(leadId);
    const { data, error } = await updateLeadValidity(leadId, isValid);
    if (error) {
      toast.error(error?.toString() || 'Failed to update lead validity');
    } else if (data) {
      // 更新本地数据
      setLeads(prevLeads =>
        prevLeads.map(lead =>
          lead.lead_id === leadId ? { ...lead, is_valid: isValid } : lead
        )
      );
      // 同时更新selectedLead状态
      if (selectedLead && selectedLead.lead_id === leadId) {
        setSelectedLead({ ...selectedLead, is_valid: isValid });
      }
      toast.success(commonT('success'), {
        description: isValid ? t('markedValid') : t('markedInvalid')
      });
    }
    setUpdatingLeadId(null);
  };
  useEffect(() => {
    fetchLeads();
  }, []);
  return (
    <div className="container mx-auto py-6">
      <div className="flex items-center justify-between mb-6">
        <CardTitle>{t('title')}</CardTitle>
        <Button
          variant="outline"
          onClick={fetchLeads}
          disabled={loading}
        >
          {loading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              {commonT('loading')}
            </>
          ) : commonT('refresh')}
        </Button>
      </div>
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t('id')}</TableHead>
              <TableHead>{t('type')}</TableHead>
              <TableHead>{t('score')}</TableHead>
              <TableHead>{t('reason')}</TableHead>
              <TableHead>{t('status')}</TableHead>
              <TableHead>{t('createdAt')}</TableHead>
              <TableHead>{commonT('actions')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={8} className="h-24 text-center">
                  <Loader2 className="mx-auto h-6 w-6 animate-spin" />
                  <div className="mt-2">{commonT('loading')}</div>
                </TableCell>
              </TableRow>
            ) : leads.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="h-24 text-center">
                  {t('noData')}
                </TableCell>
              </TableRow>
            ) : (
              leads.map((lead) => (
                <TableRow key={lead.lead_id}>
                  <TableCell className="font-mono text-xs">
                    {lead.lead_id}
                  </TableCell>
                  <TableCell>
                    <Badge variant={lead.type === 'creator' ? 'default' :
                      lead.type === 'post' ? 'secondary' : 'outline'}>
                      {getTypeLabel(lead.type)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {lead.lead_score ?? '-'}
                  </TableCell>
                  <TableCell className="max-w-[200px] truncate">
                    {lead.reason || '-'}
                  </TableCell>
                  <TableCell>
                    {lead.is_valid === true ? (
                      <Badge variant="default" className="bg-green-500">
                        {t('valid')}
                      </Badge>
                    ) : lead.is_valid === false ? (
                      <Badge variant="destructive">
                        {t('invalid')}
                      </Badge>
                    ) : (
                      <Badge variant="outline">
                        {t('pending')}
                      </Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    {dayjs(lead.created_at).format('YYYY-MM-DD HH:mm:ss')}
                  </TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openLeadDetails(lead)}
                        className="flex items-center gap-1"
                      >
                        <Info className="h-4 w-4" />
                        {commonT('details')}
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openDeleteConfirm(lead.lead_id)}
                        disabled={deletingLeadId === lead.lead_id}
                        className="flex items-center gap-1 text-red-500 hover:text-red-700"
                      >
                        {deletingLeadId === lead.lead_id ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <Trash2 className="h-4 w-4" />
                        )}
                        {commonT('delete')}
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
      {/* 线索详情弹窗 */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{t('detailsTitle')}</DialogTitle>
            <DialogDescription>
              {t('detailsDescription')}
            </DialogDescription>
          </DialogHeader>

          {selectedLead && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">{t('id')}</p>
                  <p className="font-mono text-xs break-all">{selectedLead.lead_id}</p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">{t('type')}</p>
                  <Badge variant={selectedLead.type === 'creator' ? 'default' :
                    selectedLead.type === 'post' ? 'secondary' : 'outline'}>
                    {getTypeLabel(selectedLead.type)}
                  </Badge>
                </div>
              </div>
              {selectedLead.type === 'creator' ? (
                <div>
                  <div className="grid grid-cols-2 gap-4 mb-2">
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">user name</p>
                      <p className="font-mono text-xs break-all">{creatorDetails?.username?.toString() || 'loading...'}</p>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">platform</p>
                      <p className="font-mono text-xs break-all">{creatorDetails?.platform?.toString() || 'loading...'}</p>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4 mb-2">
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">bio</p>
                      <p className="font-mono text-xs break-all">{creatorDetails?.bio?.toString()}</p>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">follower count</p>
                      <p className="font-mono text-xs break-all">{creatorDetails?.follower_count?.toString()}</p>
                    </div>
                  </div>
                </div>
              ) : (
                <div>
                  <div className="grid grid-cols-2 gap-4 mb-2">
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">platform</p>
                      <p className="font-mono text-xs break-all">{postDetails?.platform || 'loading...'}</p>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">title</p>
                      <p className="font-mono text-xs break-all">{postDetails?.title || 'loading...'}</p>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4 mb-2">
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">content</p>
                      <p className="font-mono text-xs break-all">{postDetails?.content?.toString() || 'loading...'}</p>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">like count</p>
                      <p className="font-mono text-xs break-all">{postDetails?.like_count?.toString() || 'loading...'}</p>
                    </div>
                  </div>
                </div>
              )}

              <div>
                <div className="flex justify-between items-center">
                  <p className="text-sm font-medium text-muted-foreground">{t('score')}</p>
                  {!isEditing && (
                    <Button variant="ghost" size="sm" onClick={startEditing} className="h-8 px-2">
                      <Edit className="h-4 w-4 mr-1" />
                      {commonT('edit')}
                    </Button>
                  )}
                </div>
                {isEditing ? (
                  <Input
                    type="number"
                    value={editScore !== null ? editScore : ''}
                    onChange={(e) => setEditScore(e.target.value ? Number(e.target.value) : null)}
                    placeholder={t('scorePlaceholder')}
                    className="mt-1"
                  />
                ) : (
                  <p>{selectedLead.lead_score ?? '-'}</p>
                )}
              </div>

              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('reason')}</p>
                {isEditing ? (
                  <Textarea
                    value={editReason}
                    onChange={(e) => setEditReason(e.target.value)}
                    placeholder={t('reasonPlaceholder')}
                    className="mt-1"
                    rows={3}
                  />
                ) : (
                  <p className="text-sm">{selectedLead.reason || '-'}</p>
                )}
              </div>

              {isEditing && (
                <div className="flex justify-end space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={cancelEditing}
                    disabled={isSaving}
                  >
                    <X className="h-4 w-4 mr-1" />
                    {commonT('cancel')}
                  </Button>
                  <Button
                    variant="default"
                    size="sm"
                    onClick={saveEditing}
                    disabled={isSaving}
                  >
                    {isSaving ? (
                      <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                    ) : (
                      <Save className="h-4 w-4 mr-1" />
                    )}
                    {commonT('save')}
                  </Button>
                </div>
              )}

              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('status')}</p>
                {selectedLead.is_valid === true ? (
                  <Badge variant="default" className="bg-green-500">
                    {t('valid')}
                  </Badge>
                ) : selectedLead.is_valid === false ? (
                  <Badge variant="destructive">
                    {t('invalid')}
                  </Badge>
                ) : (
                  <Badge variant="outline">
                    {t('pending')}
                  </Badge>
                )}
              </div>

              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('createdAt')}</p>
                <p>{dayjs(selectedLead.created_at).format('YYYY-MM-DD HH:mm:ss')}</p>
              </div>
            </div>
          )}

          <DialogFooter className="flex justify-between items-center">
            <div className="flex space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => selectedLead && handleUpdateValidity(selectedLead.lead_id, true)}
                disabled={selectedLead?.is_valid === true || updatingLeadId === selectedLead?.lead_id}
                className="flex items-center gap-1"
              >
                {updatingLeadId === selectedLead?.lead_id ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <CheckCircle className="h-4 w-4" />
                )}
                {t('markValid')}
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => selectedLead && handleUpdateValidity(selectedLead.lead_id, false)}
                disabled={selectedLead?.is_valid === false || updatingLeadId === selectedLead?.lead_id}
                className="flex items-center gap-1"
              >
                {updatingLeadId === selectedLead?.lead_id ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <XCircle className="h-4 w-4" />
                )}
                {t('markInvalid')}
              </Button>
            </div>
            <Button variant="secondary" onClick={() => setDialogOpen(false)}>
              {commonT('close')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      {/* 删除确认对话框 */}
      <AlertDialog open={deleteAlertOpen} onOpenChange={setDeleteAlertOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{commonT('delete')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('deleteConfirm')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{commonT('cancel')}</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteLead} className="bg-red-500 hover:bg-red-700">
              {commonT('delete')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}